package com.it.xyx;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname UserShiroController
 * @Description TODO
 * @Date 2024/8/23 20:12
 * @Created by 潜伏Sir
 */
@Controller
@RequestMapping("/")
public class UserShiroController {

    /**
     * @Author: 潜伏Sir
     * @Description:
     * @DateTime: 20:16 2024/8/23
     * @Params:
     * @Return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 如果当前用户未进行认证
        if (!currentUser.isAuthenticated()) {
            // 将用户名和密码加密封装为token
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 执行登录
                currentUser.login(token);
            } catch (UnknownAccountException uae) { // 用户名不存在
                model.addAttribute("errorMsg", "用户名不存在！");
                return "login";
            } catch (IncorrectCredentialsException ice) { // 密码错误
                model.addAttribute("errorMsg", "密码错误！");
                return "login";
            }
        }
        return "index";

    }

    /*
     * @description: 默认跳转
     * @Description TODO
     * @Date 2024/8/23 20:12
     * @Created by 潜伏Sir
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /*
     * @description: 默认跳转
     * @Description TODO
     * @Date 2024/8/23 20:12
     * @Created by 潜伏Sir
     */
    @RequestMapping("")
    public String toIndexPage(Model model) {
        model.addAttribute("key", "Shiro安全框架");
        return "index";
    }

    /*
     * @description: 跳往添加页面
     * @Description TODO
     * @Date 2024/8/23 20:12
     * @Created by 潜伏Sir
     */
    @RequestMapping("/user/add")
    public String toAddPage() {
        return "/add";
    }

    /*
     * @description: 跳往编辑修改页面
     * @Description TODO
     * @Date 2024/8/23 20:12
     * @Created by 潜伏Sir
     */
    @RequestMapping("/user/edit")
    public String toEditPage() {
        return "/edit";
    }

    @ResponseBody
    @RequestMapping("/noAuth")
    public String noAuth() {
        return "您没有权限访问该资源！";
    }

}
